/**   
* @Title: CommonApiUtil.java 
* @Package com.zjdiepu.www.util 
* 
* @author zhangpp
* @date 2017年6月1日 下午7:17:03 
* @version V1.0   
*/
package com.zjdiepu.www.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SimpleTimeZone;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**      
 * 项目名称：diepu-parent-base   
 * 类名称：CommonApiUtil   
 * 类描述：   
 * 创建人：zhangpp
 * 创建时间：2017年6月1日 下午7:17:03   
 * 修改人：zhangpp
 * 修改时间：2017年6月1日 下午7:17:03   
 * 修改备注：   
 * @version V1.0     
 */
public class CommonApiUtil {

	private static String SEND_URL = "http://v.juhe.cn/sms/send";
	private static String APPKEY = "8eaab27f59024b92e20e73f35fe58a00";
	private static String TPL_ID = "39143";
	
	/**
	 * 短信发送工具类
	 * @param mobile 手机号
	 * @param verifyCode 验证码
	 * @return 返回短信平台的返回值信息
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String messageUtil(String mobile,String code,String message) throws HttpException, IOException {
		String verifyCode = "#code#="+code+"&#message#="+message;
		HttpClient client = new HttpClient();  
        PostMethod post = new PostMethod(SEND_URL);  
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] data = 
        { 
    		new NameValuePair("mobile", mobile), // 手机号码
            new NameValuePair("tpl_id", TPL_ID), // 模板ID
            new NameValuePair("tpl_value", verifyCode), // 内容
            new NameValuePair("key", APPKEY) 
        };
        post.setRequestBody(data);  
        client.executeMethod(post);  
        String result = new String(post.getResponseBodyAsString().getBytes(), "utf-8");
        post.releaseConnection();
		return result;
	}
	
	
   private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    private static String formatIso8601Date(Date date) {

        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);

        df.setTimeZone(new SimpleTimeZone(0, "GMT"));

        return df.format(date);

    }
    
    private static final String ENCODING = "UTF-8";

    private static String percentEncode(String value) throws UnsupportedEncodingException 
    {
        return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null;
    }
    
    
    public static String getSignature() throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException
	{
	    final String HTTP_METHOD = "GET";

        Map<String, String> parameters = new HashMap<String, String>();
        
        // 加入请求参数
        parameters.put("Action", "DescribeRegions");
        parameters.put("Version", "2014-08-15");
        parameters.put("AccessKeyId", "LTAIroOjAUdAuM7r");
        parameters.put("TimeStamp", formatIso8601Date(new Date()));
        parameters.put("SignatureMethod", "HMAC-SHA1");
        parameters.put("SignatureVersion", "1.0");
        parameters.put("SignatureNonce", CommonUtil.getUUID());
        parameters.put("Format", "JSON");
        
        String[] sortedKeys = parameters.keySet().toArray(new String[]{});
        //Arrays.sort(sortedKeys);
        
        final String SEPARATOR = "&";
        
        // 生成stringToSign字符串
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(HTTP_METHOD).append(SEPARATOR);
        stringToSign.append(percentEncode("/")).append(SEPARATOR);
        
        
        StringBuilder canonicalizedQueryString = new StringBuilder();
        
        for(String key:sortedKeys)
        {
        	//这里注意对key和value进行编码
        	canonicalizedQueryString.append("&").append(percentEncode(key)).append("=").append(percentEncode(parameters.get(key)));
        }
        
        //这里注意对canonicalizedQueryString进行编码
        stringToSign.append(percentEncode(canonicalizedQueryString.toString().substring(1)));
        
        //转换字符串
        String ToSign = String.valueOf(stringToSign);
        System.out.println(ToSign);
        
        
        //以下是一段计算签名的示例代码
        final String ALGORITHM = "HmacSHA1";
        final String ENCODING = "UTF-8";
        String accessKeySecret = "HiFWNLKq44Y9p1EwshqlcVtpWMuWKd&";

        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(accessKeySecret.getBytes(ENCODING), ALGORITHM));
        byte[] signData = mac.doFinal(ToSign.getBytes(ENCODING));
        String signature = new String(Base64.encodeBase64(signData));
        System.out.println(signature);
        return signature;
	}
	
	
	
	public static void aliyuncsMysql() throws HttpException, IOException, NoSuchAlgorithmException, InvalidKeyException
	{
		String URL = "https://rds.aliyuncs.com/";
		HttpClient client = new HttpClient();  
        PostMethod post = new PostMethod(URL);  
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] data = 
        { 
        	new NameValuePair("Action", "GrantAccountPrivilege"),
    		new NameValuePair("AccountName", "zpp"), 
            new NameValuePair("AccountPrivilege", "ReadOnly"), 
            new NameValuePair("DBName", "dp_test"),
            new NameValuePair("DBInstanceId", "rm-bp1bzd7s3xrre2q0y"),
            new NameValuePair("Format", "JSON"),
            new NameValuePair("Version", "2014-08-15"),
            new NameValuePair("AccessKeyId", "LTAIroOjAUdAuM7r"),
            new NameValuePair("SignatureMethod", "HMAC-SHA1"),
            new NameValuePair("SignatureNonce",CommonUtil.getUUID()),
            new NameValuePair("Timestamp", formatIso8601Date(new Date())),
            new NameValuePair("SignatureVersion", "1.0"),
            new NameValuePair("Signature", getSignature()+"%3D")
        };
        post.setRequestBody(data);  
        client.executeMethod(post);  
        String result = new String(post.getResponseBodyAsString().getBytes(), "utf-8");
        post.releaseConnection();
        System.out.println(result);
		
	}
	
	

	

 
	
	public static void main(String[] args) {
		try {
			

			aliyuncsMysql();
			
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
}
